package com.yoda.youdianda.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yoda.youdianda.common.R;
import com.yoda.youdianda.domain.YddCate;
import com.yoda.youdianda.mapper.YddCateMapper;
import com.yoda.youdianda.service.YddCateService;
import com.yoda.youdianda.vo.PageResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * @author shawn
 * @date 2022年 11月 13日 14:35
 */
@Service
public class YddCateServiceImpl implements YddCateService {

    @Autowired
    private YddCateMapper cateMapper;


    /**
     * 得到所有数据
     *
     * @return {@link List}<{@link YddCate}>
     */
    @Override
    public List<YddCate> getAllCate() {
        return cateMapper.selectList(new LambdaQueryWrapper<>());
    }

    @Override
    public R<PageResult<YddCate>> getList(String catename, String page, String limit) {

        Page<YddCate> yddCatePage = new Page<>();

        LambdaQueryWrapper<YddCate> queryWrapper = new LambdaQueryWrapper<>();

        queryWrapper.like(catename != null, YddCate::getCatename, catename);

        queryWrapper.orderByDesc(YddCate::getSortNum);

        cateMapper.selectPage(yddCatePage, queryWrapper);

        int currentPage = Integer.parseInt(page);

        int pageSize = Integer.parseInt(limit);

        PageResult<YddCate> pageResult = new PageResult<>(currentPage, pageSize, (int) yddCatePage.getTotal(), yddCatePage.getRecords());

        return R.success(pageResult);
    }

    @Override
    public YddCate getById(Integer cateid) {
        return cateMapper.selectById(cateid);
    }

    @Override
    public YddCate getYddCate(Integer cateid) {
        YddCate yddCate = cateMapper.selectById(cateid);
        return yddCate;
    }

    @Override
    public R<YddCate> row(String id) {
        YddCate yddCate = cateMapper.selectById(id);
        return R.success(yddCate);
    }

    @Override
    public R<String> add(YddCate yddCate) {
        yddCate.setDefaultData("0");
        cateMapper.insert(yddCate);
        return R.success("新增成功!");
    }

    @Override
    public R<String> updateCate(YddCate yddCate) {
        cateMapper.updateById(yddCate);
        return R.success("修改成功!");
    }

    @Override
    public R<String> delete(int id) {
        YddCate yddCate = cateMapper.selectById(id);
        // 是默认数据,不可删除
        if ("1".equals(yddCate.getDefaultData())) {
            return R.success("系统默认数据，不允许删除", 100);
        }
        cateMapper.deleteById(id);
        return R.success("");
    }

    @Override
    public R<List<YddCate>> all() {
        LambdaQueryWrapper<YddCate> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByDesc(YddCate::getSortNum);
        List<YddCate> list = cateMapper.selectList(queryWrapper);
        return R.success(list);
    }
}